package com.tarena.lbs.activity.dao.repository.impl;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.tarena.lbs.activity.dao.mapper.ActivityMapper;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.common.utils.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import java.nio.charset.StandardCharsets;
import java.util.Base64;
import java.util.Date;

@Slf4j
@Repository
public class ActivityRepositoryImpl implements ActivityRepository {

    @Autowired
    private ActivityMapper activityMapper;
    @DubboReference
    private UserApi userApi;
    @Override
    public void saveActivity(ActivityAddParam param) {
        ActivityPO activityPO=assemblePoToDto(param);
        Integer userId = getUserIdFromHeader();
        log.debug("登录人userId:{}",userId);
        AdminDto dto =userApi.getAdminById(userId);
        //当前商家的id
        Integer businessId=dto.getBusinessId();
        activityPO.setRewardCouponId(param.getRewardCouponId().toString());
        activityPO.setBusinessId(businessId);
        activityMapper.insert(activityPO);
    }
    private ActivityPO assemblePoToDto(ActivityAddParam param) {
        ActivityPO activityPO=new ActivityPO();
        BeanUtils.copyProperties(param,activityPO);
        activityPO.setStatus(1);
        activityPO.setCreateAt(new Date());
        activityPO.setUpdateAt(new Date());
        return activityPO;
    }
    private Integer getUserIdFromHeader() {
        try {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes == null) return null;
            HttpServletRequest request = attributes.getRequest();
            String token = request.getHeader("authorization");
            log.debug("tokenn:{}",token);
            if (StringUtils.isNotBlank(token)) {
                Integer number=parseUserIdFromToken(token);
                log.debug("用户number:{}",number);
                return number;
            }
            return null;
        } catch (Exception e) {
            log.error("从请求头获取用户ID失败", e);
            return null;
        }
    }
    private Integer parseUserIdFromToken(String token) {
        try {
            // JWT token 由三部分组成，用点分隔：Header.Payload.Signature
            String[] parts = token.split("\\.");
            if (parts.length != 3) {
                log.warn("JWT token 格式不正确");
                return null;
            }
            // 解码 Payload 部分 (Base64Url)
            String payload = new String(Base64.getUrlDecoder().decode(parts[1]), StandardCharsets.UTF_8);
            // 解析 JSON payload
            ObjectMapper objectMapper = new ObjectMapper();
            JsonNode payloadNode = objectMapper.readTree(payload);
            // 根据你的 JWT 结构获取用户ID
            // 从你的 token 看，payload 包含一个 payload 字段，里面是用户信息
            if (payloadNode.has("payload")) {
                String innerPayload = payloadNode.get("payload").asText();
                JsonNode userInfo = objectMapper.readTree(innerPayload);

                if (userInfo.has("id")) {
                    return userInfo.get("id").asInt();
                }
            }
            // 或者直接查找 id 字段
            if (payloadNode.has("id")) {
                return payloadNode.get("id").asInt();
            }
            log.warn("在 JWT token 中未找到用户ID");
            return null;
        } catch (Exception e) {
            log.error("解析 JWT token 失败", e);
            return null;
        }
    }
}
